//
//  HotelDetailsController.swift
//  AirTravel
//
//  Created by apple on 2021/7/19.
//

import UIKit
import JXBanner
import JXPageControl
import FWPopupView
import HandyJSON
class HotelDetailsController: UIViewController {

    @IBOutlet weak var tabView: UITableView!
    @IBOutlet weak var topLine: NSLayoutConstraint!
    
    
    
    let identifyHDH = "HotelDetailsHeadCell"
    let idnetifyRL = "RoomListCell"
    let identifyHH = "HotelHeaderView"
    let identifyCP = "CurrentPoliticsCell"
    let identifyBOC = "BottomOfCell"
    let identifyP = "Pure1Cell"
//    let identifyES = "EvaluationScoreCell"
//    let identifyECC = "EvaluationContentCell"
//    let identifyHL = "HotelListCell"
    
    
    
    var time1 = ""
    var time2 = ""
    var cityId = ""
    var hotelId = ""
    var scoreArray = [""]
    
    var hotelDetail:CityHotelMianModel?
    
    var hotelDetailList:CityHotelDetailMianModel?
    
    
    lazy var banner: JXBanner = {
        let banner = JXBanner()
        banner.placeholderImgView.image = UIImage(named: "banner_placeholder")
        banner.delegate = self
        banner.tag = 0
        banner.dataSource = self
        banner.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 294)
        return banner
    }()
    
    lazy var hotelTagViewModel: HotelTagViewModel = {
        let iconView = HotelTagViewModel()
        iconView.delegate = self
        return iconView
    }()
    
    lazy var hotelViewModel: HotelTagViewModel = {
        let iconView = HotelTagViewModel()
        iconView.delegate = self
        return iconView
    }()
    
    lazy var roomViewModel: HotelTagViewModel = {
        let iconView = HotelTagViewModel()
        iconView.delegate = self
        return iconView
    }()
    
    lazy var facilitiesViewModel: HotelFacilitiesViewModel = {
        let iconView = HotelFacilitiesViewModel()
        iconView.delegate = self
        return iconView
    }()
 
    
    lazy var scoreViewModel: HotelFacilitiesViewModel = {
        let iconView = HotelFacilitiesViewModel()
        iconView.delegate = self
        return iconView
    }()
    
    lazy var evaluationViewModel: EvaluationImageViewModel = {
        let iconView = EvaluationImageViewModel()
        iconView.delegate = self
        return iconView
    }()
    
    lazy var detailsBedView: DetailsBedView = {
        let customPopupView = DetailsBedView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT * 0.8))
        
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "1"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if SCREEN_HEIGHT >= 812 {
            self.topLine.constant = 88
        }else{
            self.topLine.constant = 64
        }
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.estimatedRowHeight = 100
        self.tabView.rowHeight = UITableView.automaticDimension
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "HotelDetailsHeadCell", bundle: nil), forCellReuseIdentifier: identifyHDH)
        self.tabView.register(UINib.init(nibName: "RoomListCell", bundle: nil), forCellReuseIdentifier: idnetifyRL)
        self.tabView.register(UINib.init(nibName: "HotelHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: identifyHH)
        self.tabView.register(UINib.init(nibName: "CurrentPoliticsCell", bundle: nil), forCellReuseIdentifier: identifyCP)
        self.tabView.register(UINib.init(nibName: "BottomOfCell", bundle: nil), forCellReuseIdentifier: identifyBOC)
        self.tabView.register(UINib.init(nibName: "Pure1Cell", bundle: nil), forCellReuseIdentifier: identifyP)
//        self.tabView.register(UINib.init(nibName: "EvaluationScoreCell", bundle: nil), forCellReuseIdentifier: identifyES)
//        self.tabView.register(UINib.init(nibName: "EvaluationContentCell", bundle: nil), forCellReuseIdentifier: identifyECC)
//        self.tabView.register(UINib.init(nibName: "HotelListCell", bundle: nil), forCellReuseIdentifier: identifyHL)
        if #available(iOS 11.0, *) {
            self.tabView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = true
        }
        
        
        getData()
    }
    
    
    func getData(){
        
        
         NetWorkRequest(API1.searchHotelDetail(parameters: ["cityId":self.cityId ,"checkInDate":self.time1,"checkOutDate":self.time2,"hotelId":self.hotelId]), completion: {[weak self] (responseString) -> (Void) in
            guard let model = JSONDeserializer<CityHotelMianModel>.deserializeFrom(json: "\(responseString["data"])") else {
                return
                
            }

            self?.hotelDetail = model
            self?.searchHotelPrice()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常,超时")
        })
    }
    
    //床型
    func searchHotelPrice(){
        
        NetWorkRequest(API1.searchHotelPrice(parameters: ["cityId":self.cityId ,"checkInDate":self.time1,"checkOutDate":self.time2,"hotelId":self.hotelId]), completion: {[weak self] (responseString) -> (Void) in
           guard let model = JSONDeserializer<CityHotelDetailMianModel>.deserializeFrom(json: "\(responseString)") else {
               return
               
           }
            
           self!.hotelDetailList = model

        self?.hotelDetailList = model
            self?.tabView.reloadData()
//        self!.getCommentList()
       }, failed: { (failedResutl) -> (Void) in
           print("服务器返回code不为0000啦~\(failedResutl)")
       }, errorResult: { () -> (Void) in
           print("网络异常,超时")
       })
        
    }
    
    func getCommentList(){
        NetWorkRequest(API1.getCommentList(parameters: ["hotelid":self.hotelId]), completion: {[weak self] (responseString) -> (Void) in
            
            self?.tabView.reloadData()
//           guard let model = JSONDeserializer<CityHotelMianModel>.deserializeFrom(json: "\(responseString["data"])") else {
//               return
//
//           }
//
//           self?.hotelDetail = model
           
       }, failed: { (failedResutl) -> (Void) in
           print("服务器返回code不为0000啦~\(failedResutl)")
       }, errorResult: { () -> (Void) in
           print("网络异常,超时")
       })
    }

    @IBAction func backBtn(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func bottom(sender:UIButton) {
        print("\(sender.tag)")
        switch sender.tag {
        case 6:
            let vc = WebsiteReviewsController()
            self.navigationController?.pushViewController(vc, animated: true)
        default:
            let vc = DetailsHotelFacilitiesController()
            vc.hotelDetail = hotelDetail
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    //普通房间预定
    @objc func generalOrder(sender:UIButton) {
        let vc = BookingHotelController()
        vc.time2 = time2
        vc.time1 = time1
        vc.cityId = cityId
        vc.hotelId = hotelId
        vc.hotelDetail = hotelDetail
        vc.hotelDetailList = hotelDetailList?.data?[sender.tag]
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func address() {//跳转外部导航
//        let vc = HotelMapController()
//        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension HotelDetailsController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int{
        return 4
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        case 2:
            return 3
        case 3:
            return 2
//        case 4:
//            return 1
        case 1:
            return hotelDetailList?.data?.count ?? 0
//        case 5 + self.scoreArray.count:
//            return 10
        default:
            return 3
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyHDH) as! HotelDetailsHeadCell
            cell.titleLab.text = hotelDetail?.hotelName
            
            cell.introductionLab.text = "\(hotelDetail?.bulitTime.substring(to: 3) ?? "")年装修"
            cell.scoreBtn.setTitle(hotelDetail?.hotelStarRate, for: .normal)
            cell.addressLab.text = hotelDetail?.zoneName
            cell.selectionStyle = .none
            cell.bannerView.addSubview(self.banner)
            
            
            let timeDate = stringFormatToDate(timeString: time1, format: "yyyy-MM-dd")
            
            let timeDate1 = stringFormatToDate(timeString: time2, format: "yyyy-MM-dd")
            
            getTwoDate(date: timeDate, date1: timeDate1) { [weak self] result in
                print("**********\(result)")
                
                cell.stateBtn.setTitle(result[0].0, for: .normal)
                cell.endBtn.setTitle(result[1].0, for: .normal)
                cell.stateLab.text = result[0].1
                cell.endLab.text = result[1].1
            }
            
            let formatter = DateFormatter()
            let calendar = Calendar.current
            formatter.dateFormat = "yyyy-MM-dd"
           
            let diff:DateComponents = calendar.dateComponents([.day], from: timeDate!, to: timeDate1!)
              
            cell.fewNightsBtn.setTitle("共\(diff.day ?? 0)晚", for: .normal)
            
            
            if(hotelDetailList != nil){
                print("\(hotelDetailList?.data?[0].baseRoomInfo?.serviceNames ?? "")")
                let arraySubstrings: [Substring] = (hotelDetailList?.data?[0].baseRoomInfo?.serviceNames.split(separator: ","))!
                
                var arrayStrings: [String] = []
                for item in arraySubstrings {
                            
                    arrayStrings.append("\(item)")
                   
                }
                
                self.hotelTagViewModel.bindViewToViewModel(collView: cell.tagColl, number: 0)
                self.hotelTagViewModel.setUpdata(arrat: arrayStrings)
            }
            
            
            
     
            
            
            self.hotelViewModel.bindViewToViewModel(collView: cell.screeningColl, number: 1)
            self.hotelViewModel.setUpdata(arrat: ["大床房","含早餐","双床房"])
            cell.addressBtn.addTarget(self, action: #selector(address), for: .touchUpInside)
            return cell
        case 2:
            if indexPath.row == 2{
                let cell = tableView.dequeueReusableCell(withIdentifier: identifyBOC) as! BottomOfCell
                cell.selectionStyle = .none
                cell.btn.tag = indexPath.section
                cell.btn.addTarget(self, action: #selector(bottom(sender:)), for: .touchUpInside)
                return cell
            }
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyCP) as! CurrentPoliticsCell
            cell.contenLab.text = hotelDetail?.policy?[indexPath.row].policyText
            cell.selectionStyle = .none
            cell.separatorInset = UIEdgeInsets(top: 0, left: SCREEN_WIDTH, bottom: 0, right: 0);
            return cell
        case 3:
            if indexPath.row == 1{
                let cell = tableView.dequeueReusableCell(withIdentifier: identifyBOC) as! BottomOfCell
                cell.selectionStyle = .none
                cell.btn.tag = indexPath.section
                cell.btn.addTarget(self, action: #selector(bottom(sender:)), for: .touchUpInside)
                return cell
            }
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyP) as! Pure1Cell
            
            if(hotelDetailList != nil){
            let arraySubstrings: [Substring] = (hotelDetailList?.data?[0].baseRoomInfo?.serviceNames.split(separator: ","))!
            
            var arrayStrings: [String] = []
            for item in arraySubstrings {
                        
                arrayStrings.append("\(item)")
               
            }
            
                
                self.facilitiesViewModel.setUpdata(arrat: arrayStrings)
            }
            cell.selectionStyle = .none
            cell.separatorInset = UIEdgeInsets(top: 0, left: SCREEN_WIDTH, bottom: 0, right: 0)

            self.facilitiesViewModel.bindViewToViewModel(collView: cell.collVIew, number: 0)
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: idnetifyRL) as! RoomListCell
            cell.selectionStyle = .none
            cell.titleLab.text = hotelDetailList?.data?[indexPath.row].baseRoomInfo?.roomName
            cell.instructionsLab.text = hotelDetailList?.data?[indexPath.row].roomInfo?.first?.cancelLimitInfo?.cancelPolicyInfo
            
            cell.oldPriceLab.text = "￥" + (hotelDetailList?.data?[indexPath.row].roomInfo?.first?.roomPriceInfo?.averagePrice!.amount)!
            
            cell.priceLab.text = "￥" + (hotelDetailList?.data?[indexPath.row].roomInfo?.first?.roomPriceInfo?.averagePrice?.settleFee)!
            self.roomViewModel.bindViewToViewModel(collView: cell.collView, number: 2)
            self.roomViewModel.setUpdata(arrat: ["榻榻米","足疗","管家服务"])
            
//            print("\(hotelDetail?.roomPriceItem?[indexPath.row].roomImageUrl)")
            cell.img.kf.setImage(with: URL.init(string: hotelDetail?.roomPriceItem![indexPath.row].baseRoomInfo?.roomImageUrl ?? ""))
            cell.orderBtn.tag = indexPath.row
            if indexPath.section == 1 {
                
                cell.orderBtn.tag = indexPath.row
                cell.orderBtn.addTarget(self, action: #selector(generalOrder(sender:)), for: .touchUpInside)
            }
            
            return cell
//        case 4:
//            let cell = tableView.dequeueReusableCell(withIdentifier: identifyES) as! EvaluationScoreCell
//            cell.selectionStyle = .none
//            cell.separatorInset = UIEdgeInsets(top: 0, left: SCREEN_WIDTH, bottom: 0, right: 0)
//            self.scoreViewModel.bindViewToViewModel(collView: cell.collView, number: 1)
//            return cell
//        case 5 + self.scoreArray.count:
//            let cell = tableView.dequeueReusableCell(withIdentifier: identifyHL) as! HotelListCell
//            cell.selectionStyle = .none
//            return cell
        default:
            if indexPath.row == 2{
                let cell = tableView.dequeueReusableCell(withIdentifier: identifyBOC) as! BottomOfCell
                cell.selectionStyle = .none
                cell.btn.tag = indexPath.section
                cell.btn.addTarget(self, action: #selector(bottom(sender:)), for: .touchUpInside)
                return cell
            }
//            switch indexPath.row {
//            case 0:
//                let cell = tableView.dequeueReusableCell(withIdentifier: identifyECC) as! EvaluationContentCell
//                cell.selectionStyle = .none
//                cell.separatorInset = UIEdgeInsets(top: 0, left: SCREEN_WIDTH, bottom: 0, right: 0)
//                return cell
//            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: identifyP) as! Pure1Cell
                cell.selectionStyle = .none
                cell.separatorInset = UIEdgeInsets(top: 0, left: SCREEN_WIDTH, bottom: 0, right: 0)
                self.evaluationViewModel.bindViewToViewModel(collView: cell.collVIew)
                return cell
//            }
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        switch indexPath.section {
        case 0:
            return 563
        case 2:
            return UITableView.automaticDimension
        case 3:
            return 80
//        case 4:
//            return 160
        case 1:
            return 170
//        case 5 + self.scoreArray.count:
//            return 158
        default:
            switch indexPath.row {
            case 1:
                return ((SCREEN_WIDTH - 42) / 3 + 6) * 2
            default:
                return UITableView.automaticDimension
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        switch section {
        case 2,3:
            return 50
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        switch section {
        case 1:
            return 8
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifyHH) as! HotelHeaderView
        switch section {
//        case 2:
//            headView.titleLab.text = "钟点房"
//            headView.img.isHidden = true
//            headView.leftLine.constant = 18
        case 2:
            headView.titleLab.text = "政策必读"
            headView.img.isHidden = false
            headView.leftLine.constant = 47
        case 3:
            headView.titleLab.text = "设施"
            headView.img.isHidden = true
            headView.leftLine.constant = 18
//        case 4:
//            headView.titleLab.text = "网友评价"
//            headView.img.isHidden = true
//            headView.leftLine.constant = 18
//        case 5 + self.scoreArray.count:
//            headView.titleLab.text = "附近酒店"
//            headView.img.isHidden = true
//            headView.leftLine.constant = 18
        default:
            headView.img.isHidden = true
            headView.titleLab.isHidden = true
        }
        return headView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        let footerView = UIView.init()
        footerView.backgroundColor = UIColor.groupTableViewBackground
        return footerView
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        switch indexPath.section {
        case 1:
            self.detailsBedView.model = hotelDetailList?.data?[indexPath.row]
            
            self.detailsBedView.img = hotelDetail?.roomPriceItem![indexPath.row].baseRoomInfo?.roomImageUrl ?? ""
            self.detailsBedView.show()
            
        default:
            break
        }
    }
}

extension HotelDetailsController:HotelTagDelegate{
    func HotelTagClick(data: NSDictionary) {
        
    }
}

extension HotelDetailsController:HotelFacilitiesDelegate{
    func hotelFacilitiesClick(data: NSDictionary) {
        
    }
}

extension HotelDetailsController:EvaluationDelegate{
    func evaluationClick(data: NSDictionary) {
        
    }
}

extension HotelDetailsController:DetailsBedDelegate{
    func detailsBedClick(data: Dictionary<String, Any>) {
        
    }
    
    
}
extension HotelDetailsController:JXBannerDataSource,JXBannerDelegate{
    
    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return 3
    }
    
    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {
        return JXBannerCellRegister(type: nil,
                                    reuseIdentifier: "HomeBannerColl",
                                    nib: UINib(nibName: "HomeBannerColl", bundle: Bundle.main))
    }
    
    func jxBanner(_ banner: JXBannerType, cellForItemAt index: Int, cell: UICollectionViewCell) -> UICollectionViewCell {
        if let tempCell = cell as? HomeBannerColl {
//            if let array = self.banners {
//                let dic = array[index] as! Dictionary<String,Any>
//                tempCell.img.kf.setImage(with: URL.init(string: "\(dic["img"] ?? "")"))
//
//            }
            tempCell.img.image = UIImage.init(named: "图层59")
        }
        return cell
    }
    
    func jxBanner(_ banner: JXBannerType,
                  layoutParams: JXBannerLayoutParams)
        -> JXBannerLayoutParams {
        return layoutParams
            .itemSize(CGSize(width: SCREEN_WIDTH, height: 294))
    }
    
    func jxBanner(pageControl banner: JXBannerType, numberOfPages: Int, coverView: UIView, builder: JXBannerPageControlBuilder) -> JXBannerPageControlBuilder {
        let pageControl = JXPageControlScale()
        pageControl.contentMode = .bottomRight
        pageControl.activeSize = CGSize(width: 15, height: 6)
        pageControl.inactiveSize = CGSize(width: 6, height: 6)
        pageControl.activeColor = UIColor.white
        pageControl.inactiveColor = UIColor.white
        pageControl.columnSpacing = 0
        pageControl.isAnimation = true
        builder.pageControl = pageControl
        builder.layout = {
            pageControl.snp.makeConstraints { (maker) in
                maker.left.right.equalTo(coverView)
                maker.top.equalTo(coverView.snp.bottom).offset(-80)
                maker.height.equalTo(20)
            }
        }
        return builder
    }
    
    func jxBanner(_ banner: JXBannerType, params: JXBannerParams) -> JXBannerParams {
        return params.timeInterval(3)
    }
    
    func jxBanner(_ banner: JXBannerType,
                      didSelectItemAt index: Int) {
        
    }

}
